package com.kaifamiao.handling;

/**
 * 1、try { } catch( ExceptionType ex ) { }
 * 2、try { } catch( ExceptionType ex ) { } catch ( ExceptionType ex ) { }
 * 3、try { } catch( ExceptionType1 | ExceptionType2 ex ) { }
 * 4、try { } catch( ExceptionType ex ) { } finally { }
 * 5、try { } finally { }
 */
public class TryCatchFinally {

    public static void main(String[] args) {

        System.out.println( "main start" );

        try {
            Object o = null;
            String s = o.toString();
            System.out.println(s);
        } catch ( Exception ex ) {
            System.out.println( ex );
        }

        System.out.println( "- ".repeat( 30 ) );

        try {
            Integer a = 100;
            Integer b = 0;
            System.out.println(a / b);
        } catch ( NullPointerException npe ) {
            System.out.println( "参与除法运算的两个值不能是null");
            System.out.println( npe );
        } catch ( ArithmeticException ae ) {
            System.out.println( "除数不能为零" );
            System.out.println( ae );
        }

        System.out.println( "- ".repeat( 30 ) );

        try {
            Integer a = 100;
            Integer b = 0;
            System.out.println(a / b);
        }
        // 从 JDK 1.7 开始 允许在 catch 之后的 ( ) 内指定多个异常类型
        catch ( NullPointerException | ArithmeticException ex ) {
            System.out.println( "出错了" );
            System.out.println( ex );
        }

        System.out.println( "- ".repeat( 30 ) );

        try {
            System.out.println( "TRY");
            Long x = 100L;
            Long y = (long)( Math.random() * 2 );
            Long r = x / y;
            System.out.println( "result: " + r );
        } catch ( ArithmeticException ae ) {
            System.out.println( "CATCH");
            System.out.println( ae );
        } finally {
            System.out.println( "FINALLY" );
        }

        System.out.println( "- ".repeat( 30 ) );

        try {
            char[] chars = {};
            System.out.println( chars[0] ); // ArrayIndexOutOfBoundsException
        } finally {
            System.out.println( "finally" );
        }

        System.out.println( "main end" );

    }

}
